/*
 * Copyright (C) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the 'License');
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an 'AS IS' BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "napi/native_api.h"

#include "imageknife.h"
#include "imageknife_type.h"
#include "imageknife_task.h"

static std::string decode_name = "default DecodeInterceptor";

using namespace ImageKnifePro;
namespace ImageKnifeTest {
class DecodeInterceptorTest : public DecodeInterceptor {
public:
    DecodeInterceptorTest()
    {
        name = "DecodeInterceptorTest";
    }

    bool Resolve(std::shared_ptr<ImageKnifeTask> task) override
    {
        if (task->product.imageBuffer != nullptr) {
            return Decode((uint8_t *)task->product.imageBuffer.get(), task->product.imageLength, task);
        }
        return false;
    }

    void Cancel(std::shared_ptr<ImageKnifeTask> task) override
    {
        task->cancelInfo = "Cancel Decode Success";
    }

private:
    bool Decode(uint8_t *buffer, uint32_t length, std::shared_ptr<ImageKnifeTask> task)
    {
        task->EchoError("Custom Decode Image Failed");
        decode_name = name;
        return false;
    }
};

static napi_value DecoderInterceptorGetName(napi_env env, napi_callback_info info)
{
    napi_value result;
    napi_create_string_utf8(env, decode_name.c_str(), decode_name.length(), &result);
    return result;
}

static napi_value SetDecoderInterceptor(napi_env env, napi_callback_info info)
{
    auto imageLoader = ImageKnifePro::ImageKnifeLoader::CreateDefaultImageLoader();
    auto interceptor = new DecodeInterceptorTest();
    imageLoader->AddDecodeInterceptor(std::shared_ptr<DecodeInterceptorTest> (interceptor));
    ImageKnifePro::ImageKnife::GetInstance().SetDefaultImageKnifeLoader(imageLoader);
    return nullptr;
}

napi_value DecoderInterceptorSetupTests(napi_env env, napi_value &exports)
{
    napi_property_descriptor desc[] = {
        { "SetDecoderInterceptor", nullptr, SetDecoderInterceptor, nullptr, nullptr, nullptr, napi_default, nullptr },
        { "DecoderInterceptorGetName", nullptr, DecoderInterceptorGetName, nullptr, nullptr, nullptr, napi_default, nullptr }
    };
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);

    return exports;
}
}